// mängijad
var players;
// kas lubada klikke
var allowClick = false;
// mängija, kes pole bot
var HUMAN_PLAYER = 6;

function Player(player_no) {
	this.no = player_no;
	this.stack = 100;
	this.bet = 0;
	this.active = true;
	this.fold = function() {
		this.active = false;
		this.hideCards();
	};
	this.repaint = function(acted) {
		$('#stack' + this.no).html(this.stack);
		$('#chipinfo' + this.no).html('<b>Chips:</b> '
				+ this.bet);
		if((acted && this.active) || this.bet > 0) {
			$('#chipinfo' + this.no).css("visibility", "visible");
		}
		calculateChips(this.no, this.bet);
	};
	this.updateStack = function(stack) {
		this.stack = stack;
		$('#stack' + this.no).html(this.stack);
	};
	this.hideCards = function() {
		$('#card' + this.no + '_1').children(':first-child').animate({
		    marginBottom: "-75"
		  }, 500).fadeOut();
		$('#card' + this.no + '_2').children(':first-child').animate({
		    marginBottom: "-75"
		  }, 500).fadeOut();
	};
	this.showCards = function(card1, card2) {
		var paths = new Array(2);
		paths[0] = "images/" + card1.substring(1) + "/"
				+ card1 + ".png";
		paths[1] = "images/" + card2.substring(1) + "/"
				+ card2 + ".png";

		var i;

		for (i = 1; i < 3; i++) {
			$('#card' + this.no + '_' + i).children(':first-child')
					.attr("src", paths[i - 1]);
		}
	};
}

// chat message
function Message(content, author) {
	this.content = content;
	this.author = author;
}

// lisab message
function addMessage(content, author) {
	try {
		var chat = eval('(' + localStorage.getItem("chat") + ')');
		chat.push(new Message(content, author));
		localStorage.setItem("chat", JSON.stringify(chat));
	} catch(e) {
		alert(e);
	}
}

// lisab lauale flop kaardid
function dealFlop(cards) {
	var paths = new Array(3);
	paths[0] = "images/" + cards[0].substring(1) + "/"
	+ cards[0] + ".png";
	paths[1] = "images/" + cards[1].substring(1) + "/"
	+ cards[1] + ".png";
	paths[2] = "images/" + cards[2].substring(1) + "/"
	+ cards[2] + ".png";
	
	for (i = 1; i < 4; i++) {
		$('#flop' + i).children(':first-child')
		.attr("src", paths[i - 1]);
		$('#flop' + i).css("visibility", "visible");
	}
}

// lisab lauale turn kaardi
function dealTurn(cards) {
	var path = "images/" + cards[0].substring(1) + "/"
	+ cards[0] + ".png";
	
	$('#turn').children(':first-child')
	.attr("src", path);
	$('#turn').css("visibility", "visible");
}

// lisab lauale river kaardi
function dealRiver(cards) {
	var path = "images/" + cards[0].substring(1) + "/"
	+ cards[0] + ".png";
	
	$('#river').children(':first-child')
	.attr("src", path);
	$('#river').css("visibility", "visible");
}

// chatboxi teksti lisamine
function addText() {
	var input = $("#chatinput").val();
	if (input != "") {
		addMessage(input, 6);
		$("#textarea2").append("<b>You: </b>" + input + "<br />");
		$("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
		$("#chatinput").val("");
		botReply(input);
	}
}

// serverisse mängija chat saatmine ja vastuse töötlemine
function botReply(message) {
	$.post("ChatServlet", 
			{message: message}, 
			function(data) {
				addMessage(data.content, data.author);
				$("#textarea2").append("<b>Player " + data.author + ": </b>" + data.content + "<br />");
				$("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
			}, 
			"json");
}

// Enteri vajutusel käivitakse addText funktsioon
function pressEnter(myfield, e) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
		addText();
		return false;
	} else
		return true;
}

// mängijate käikude väljastamine
function outputText(text, initiator, scroll) {
	var str;
	if(initiator != HUMAN_PLAYER) {
		str = "Player " + initiator;
	} else {
		str = "You";
	}
	
	$("#textarea").append("<i><b>" + str + "</b>" + text + "<i>" + "<br />");
	if(scroll)
		$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
}

// mängu alguse ja võidu teadete väljastamine
function writeLog(text, type, scroll) {
	if(type == 1) {
		$("#textarea").append("<font color=red>" + text + "</font><br/>");
	} else {
		$("#textarea").append("<font color=blue><b>" + text + "</b></font><br/>");
	}
	if(scroll)
		$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
}

// mängija käigu saatmine serverisse
function sendMove(move) {
	$.post("GameServlet", 
			{move: move}, 
			function(data) {
				outputText(data.moveLog, 6, true);
				if(data.move == 0){
					players[HUMAN_PLAYER - 1].fold();
				} else {
					players[HUMAN_PLAYER - 1].stack = data.stack;
					players[HUMAN_PLAYER - 1].bet = data.bet;
					players[HUMAN_PLAYER - 1].repaint(true);
				}
				getMove();
			}, 
			"json");
}

// mängija käik
function makeMove(move) {
	disableButtons();
	sendMove(move);
}

// diiler, sb, bb nuppude varjamine
function hideButtons(dealerLocation, SBLocation, BBLocation) {
	for(var i = 1; i < 10; i++) {
		$('#dealer' + i).css("visibility", "hidden");
	}
}

// diiler, sb, bb nuppude joonistamine
function paintButtons(SBLocation, BBLocation, dealerLocation) {
	$('#dealer' + SBLocation).css("visibility", "visible")
		.children(':first-child').attr("src", "images/nupud/SB.png");
	$('#dealer' + BBLocation).css("visibility", "visible")
		.children(':first-child').attr("src", "images/nupud/BB.png");
	$('#dealer' + dealerLocation).css("visibility", "visible")
	.children(':first-child').attr("src", "images/nupud/D.png");
}

// mängijate loomine
function initPlayers() {
	players = new Array();
	for(var i = 1; i < 10; i++) {
		players.push(new Player(i));
	}
}

// chati taastamine localStoragest
function initChat() {
	var chat = eval('(' + localStorage.getItem("chat") + ')');
	for(var i = 0; i < chat.length; i++) {
		if(chat[i].author != 6) {
			$("#textarea2").append("<b>Player " + chat[i].author + ": </b>" + chat[i].content + "<br />");
		} else {
			$("#textarea2").append("<b>You: </b>" + chat[i].content + "<br />");
		}
	}
	setTimeout('getBotMessage()', 5000);
}

// serverist saadetud suvaline bottide jutt
function getBotMessage() {
	$.post("ChatServlet", 
			{getBotMessage: ""}, 
			function(data) {
				addMessage(data.content, data.author);
				$("#textarea2").append("<b>Player " + data.author + ": </b>" + data.content + "<br />");
				$("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
				getBotMessage();
			}, 
			"json");
}

// lehe laadimisel nuppude disable ja sessiooni loomine
// localStorage chat loomine või laadimine
$(document).ready(function() {
	if(localStorage.getItem("chat") == null) {
		localStorage.setItem("chat", JSON.stringify(new Array()));
	}
    disableButtons();
    initSession();
});

// sessiooni loomine
function initSession() {
	$.post("GameServlet",
			{initSession: ""},
			function(data) {
			    continueGameIfRunning();
			    initChat();
			},
			"json");
}

// pooleli oleva mängu jätkamine
function continueGameIfRunning() {
	$.post("GameServlet",
			{isRunning: ""},
			function(data) {
				if (data.isRunning) {
					//jätkame pooleli olevat mängu (alternatiiviks, muudame nupu "New Game" -> "Continue")
					startGame();
				}
			},
			"json");
}

//veebilehe laadimisel mängu seisu kontroll serverist
function initGame(restore) {
	//jQuery POST: http://api.jquery.com/jQuery.post/
	$.post("GameServlet", 
			{initGame: "",
			 sendLog: restore	
			}, 
			function(data) {
				paintButtons(data.SB, data.BB, data.dealer);
				players[HUMAN_PLAYER - 1].showCards(data.pcard1, data.pcard2);
				for(var i = 0; i < 9; i++) {
					var no = data.players[i].no;
					players[no - 1].stack = data.players[i].stack;
					players[no - 1].bet = data.players[i].bet;
					players[no - 1].active = data.players[i].active;
					players[no - 1].repaint(data.players[i].acted);
				}
				setCardsInvisible();
				resetCardImages();
				setCardsVisible();
				initCards();
				showCommunityCards(data.round, data.community);
				restorePot(data.bankSize, data.round);
				if('contesters' in data) {
					showEndState(data.contesters);
				}
				if(restore)
					restoreLog(data.log);
				if(!('contesters' in data)) {
					getMove();
				}
			}, 
			"json");
}

// kui mäng on lõppenud, siis näidata seda
function showEndState(contesters) {
	for(var i = 0; i < contesters.length; i++) {
		var id = contesters[i].no - 1;
		if('card1' in contesters[i])
			players[id].showCards(contesters[i].card1, contesters[i].card2);
	}
	$(":focus").blur();
	$("#info").css("visibility", "visible");
	allowClick = true;
}

// mängu logi taastamine serverist saadud info põhjal
function restoreLog(log) {
	for(var i = 0; i < log.length; i++) {
		if(log[i].type == 0) {
			outputText(log[i].content, log[i].player, false);
		} else {
			writeLog(log[i].content, log[i].type, false);
		}
	}
	$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
}

// pot taastamine serverist saadud info põhjal
function restorePot(bankSize, round) {
	if(round > 0) {
		$('#pot').html("<b>Pot:</b> " + bankSize);
		$('#pot').css("visibility", "visible");
		calculateChips(0, bankSize);
	}
}

// laua kaartide näitamine
function showCommunityCards(round, cards) {
	if(round > 0)
		dealFlop(cards.slice(0,3));
	if(round > 1)
		dealTurn(cards.slice(3,4));
	if(round > 2)
		dealRiver(cards.slice(4,5));
}

// käigu küsimine serverilt
function getMove() {
	//jQuery POST: http://api.jquery.com/jQuery.post/
	$.post("GameServlet", 
			{send: ""}, 
			function(data) {
				processReply(data);
			}, 
			"json");
}

// serverilt saadud käigu töötlemine
function processReply(reply) {
	if('player' in reply) {
		if(reply.player == 6) {
			enableButtons(reply.canRaise);
		} else {
			outputText(reply.moveLog, reply.player, true);
			if(reply.move == 0){
				players[reply.player - 1].fold();
			} else {
				players[reply.player - 1].stack = reply.stack;
				players[reply.player - 1].bet = reply.bet;
				players[reply.player - 1].repaint(true);
			}
			if(!('newRound' in reply))
				getMove();
		}
	} 
	
	if('newRound' in reply) {
		$('#pot').html("<b>Pot:</b> " + reply.bankSize);
		$('#pot').css("visibility", "visible");
		calculateChips(0, reply.bankSize);
		resetChipImages(1);
		hideChipInfo();
		if(reply.newRound == 1) {
			dealFlop(reply.community);
			getMove();
		} else if(reply.newRound == 2) {
			dealTurn(reply.community);
			getMove();
		} else if(reply.newRound == 3) {
			dealRiver(reply.community);
			getMove();
		} else if(reply.newRound == 4) {
			$(":focus").blur();
			$("#info").css("visibility", "visible");
			for(var i = reply.winLog.length - 1; i >= 0; i--)
				writeLog(reply.winLog[i], 1, true);
			for(var i = 0; i < reply.contesters.length; i++) {
				var id = reply.contesters[i].no - 1;
				players[id].updateStack(reply.contesters[i].stack);
				if('card1' in reply.contesters[i]) {
					players[id].showCards(reply.contesters[i].card1, reply.contesters[i].card2);
				}
			}
			allowClick = true;
		}
	}
}

// mängu alustamine
function startGame() {
	$("#start").hide();
	$("#end").show();
	
	//resetCardImages();
	resetChipImages(0);
	resetStacks();
	hideChipInfo();
	hidePotSize();
	setCardsHidden();
	
	initPlayers();
	initGame(true);
}


// kaardid nähtavaks (ainult mängu alguses)
function initCards() {
	for(var i = 1; i < 10; i++) {
		if(players[i - 1].active)
			$('#cards_' + i).css("visibility", "visible");
	}
}

// kaartide nähtavaks tegemine
function setCardsVisible() {
	for (var i = 1; i < 10; i++) {
		if(players[i - 1].active) {
			$('#card' + i + '_1').children(':first-child').css("margin-bottom", "-75px").fadeIn().animate({
			    marginBottom: "+=75"
			  }, 1000);
			$('#card' + i + '_2').children(':first-child').css("margin-bottom", "-75px").fadeIn().animate({
			    marginBottom: "+=75"
			  }, 1000);
		}	
	}
}

function setCardsInvisible() {
	for(var i = 1; i < 10; i++) {
			$('#cards_' + i).css("visibility", "hidden");
	}
}
// lauapealsete kaartide peitmine
function setCardsHidden() {
	$('#flop1').css("visibility", "hidden");
	$('#flop1').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#flop2').css("visibility", "hidden");
	$('#flop2').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#flop3').css("visibility", "hidden");
	$('#flop3').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#turn').css("visibility", "hidden");
	$('#turn').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#river').css("visibility", "hidden");
	$('#river').children(':first-child').attr("src", "images/nupud/tcard.png");
}
// žetoonide kogus laual -> nähtamatu
function hideChipInfo() {
	var i;

	for (i = 1; i < 10; i++) {
		$('#chipinfo' + i).css("visibility", "hidden");
	}
}

// peida panga suurus
function hidePotSize() {
	$('#pot').css("visibility", "hidden");
}

// bet, fold, check nuppude disable
function disableButtons() {
	$("#button2").children(":first-child").attr("disabled", true);
	$("#button3").children(":first-child").attr("disabled", true);
	$("#button4").children(":first-child").attr("disabled", true);
}

// bet, fold, check nuppude enable
function enableButtons(canRaise) {
	$("#button2").children(":first-child").attr("disabled", false);
	$("#button3").children(":first-child").attr("disabled", false);
	if(canRaise)
		$("#button4").children(":first-child").attr("disabled", false);
}

// kood tagakülje piltide taastamiseks
function resetCardImages() {
	var i;
	var j;

	for (i = 1; i < 10; i++) {
		for (j = 1; j < 3; j++) {
			if (i == HUMAN_PLAYER)
				break;
			$('#card' + i + '_' + j).children(":first-child")
					.attr("src", "images/nupud/tagakylg.png");
		}
	}

}

// žetoonipiltide eemaldamine
function resetChipImages(start) {
	for (i = start; i < 10; i++) {
		$('#chips' + i).html("");
	}
}

// anda igale mängijale uuesti 100 raha
function resetStacks() {
	var i;

	for (i = 1; i < 10; i++) {
		//players[i - 1].stack = 100;
		$('#stack' + i).html("100");
	}
}

// väljastab chippide pilte
function calculateChips(player_no, amount) {
	var playerBet = amount;
	var remainder = 0;
	var amounts = new Array(5);
	var divisors = [ 100, 25, 10, 5, 1 ];

	for ( var i = 0; i > -5; i--) {
		remainder = playerBet % divisors[i * -1];
		amounts[i + 4] = (playerBet - remainder) / divisors[i * -1];
		playerBet = remainder;
	}

	var newHtml = "";

	switch (amounts[0]) {
	case 1:
		newHtml = '<img class="chip bigshadow" src="images/nupud/zetoon_white.png"/>';
		break;
	case 2:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop2" src="images/nupud/zetoon_white.png"/>';
		break;
	case 3:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop3" src="images/nupud/zetoon_white.png"/>';
		break;
	case 4:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop3" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop4" src="images/nupud/zetoon_white.png"/>';
		break;
	default:
		break;
	}

	if (amounts[1] > 0) {
		newHtml = newHtml
				+ '<img class="chip bigshadow" src="images/nupud/zetoon_red.png"/>';
	}

	if (amounts[2] == 1) {
		newHtml = newHtml
				+ '<img class="chip bigshadow" src="images/nupud/zetoon_blue.png"/>';
	} else if (amounts[2] == 2) {
		newHtml = newHtml
				+ '<img class="chip bigshadow move-right" src="images/nupud/zetoon_blue.png"/>\
				<img class="chip smallshadow ontop2" src="images/nupud/zetoon_blue.png"/>';
	}
	
	switch (amounts[3]) {
	case 1:
		newHtml = newHtml + '<img class="chip bigshadow" src="images/nupud/zetoon_green.png"/>';
		break;
	case 2:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow ontop2" src="images/nupud/zetoon_green.png"/>';
		break;
	case 3:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow ontop3" src="images/nupud/zetoon_green.png"/>';
		break;
	default:
		break;
	}
	
	switch (amounts[4]) {
	case 1:
		newHtml = newHtml + '<img class="chip bigshadow" src="images/nupud/zetoon_black.png"/>';
		break;
	case 2:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop2" src="images/nupud/zetoon_black.png"/>';
		break;
	case 3:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop3" src="images/nupud/zetoon_black.png"/>';
		break;
	case 4:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop3" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop4" src="images/nupud/zetoon_black.png"/>';
		break;
	default:
		break;
	}
	
	if(player_no == 0) {
		var invisible = '<img class="invisible" src="images/nupud/1x1.png"/>';
		newHtml = invisible + newHtml + invisible;
	}

	$('#chips' + player_no).html(newHtml);
}

// funktsioon mängu lõpetamiseks
function endGame() {
	$("#start").show();
	$("#end").hide();
	$.post("GameServlet", 
			{end: ""},  
			function(data) {
				window.location.reload(true);
			},
			"json");
}

// mängija kliki või nupuvajutuse ootamine ja seejärel edasi liikumine
function commence() {
	if(allowClick) {
		allowClick = false;
		$("#info").css("visibility", "hidden");
		$.post("GameServlet", 
				{finish: ""}, 
				function(data) {
					resetChipImages(0);
					hideChipInfo();
					hidePotSize();
					hideButtons();
					setCardsHidden();
					resetCardImages();
					if('winner' in data) {
						if(data.winner == -1) {
							alert("Game over. You ran out of money!");
						} else if(data.winner != 6) {
							alert("Game over. Player " + data.winner + " won!");
						} else {
							alert("Game over. You won!");
						}
						endGame();
					} else {
						initGame(false);
					}
				}, 
				"json");
	}
}
//tab
$(function() {
    var $items = $('#vtab>ul>li');
    $items.mouseover(function() {
        $items.removeClass('selected');
        $(this).addClass('selected');

        var index = $items.index($(this));
        $('#vtab>div').hide().eq(index).show();
        $("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
        $("#textarea").scrollTop($("#textarea")[0].scrollHeight);
    }).eq(1).mouseover();
});
//Help buttoni image kuvamine läbi jquery lighboxi
function kuva_help() {
	//ei tööta see millegipärast ja atm panen nii, et kõik lingid lihtsalt useksid jquery-lightboxi
	//ehk piirab see pack, min-varianti ka proovisin ja ei tööta
	
	//$('a[@rel*=lightbox]').lightBox();  // valib kõik lingid, millel atribuut "lightbox"
	$('a').lightBox(); 
}